package com.aidex.web.controller.api;

import com.aidex.biz.service.SSEService;
import com.aidex.biz.utils.AliQwenUtils;
import com.aidex.common.core.controller.BaseController;
import com.aidex.web.controller.biz.AliTongYiQianWen;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 菜品信息Controller
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-04-22
 */
@RestController("SseController")
@RequestMapping("/webApi")
public class SSeController extends BaseController {

    @Autowired
    private SSEService sseService;


    private static final Map<String, Boolean> SEND_MAP = new ConcurrentHashMap<>();


    @GetMapping(value = "/createSse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter createSse(@RequestParam String uid) {

        return sseService.createSse(uid);
    }

    @GetMapping(value = "/sendProductInfo", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public SseEmitter sendProductInfo(@RequestParam String question) {
        // 增加超时时间，确保长时间对话不会断开
        SseEmitter emitter = new SseEmitter(0L); // 60秒超时

        try {
            AliTongYiQianWen.streamResponse(question, emitter);
        } catch (Exception e) {
            logger.error("AI调用异常", e);
            emitter.completeWithError(e);
        }

        return emitter;
    }


    @GetMapping(value = "/closeSse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void closeSse(@RequestParam String uid) {
        sseService.closeSse(uid);
    }


}
